#include "socket_gather_read.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif
#include "socket_private_acl.h"
#include "socket_gather.h"
#include "pfunc.h"
#include "Log.h"

SocketGahterRead::SocketGahterRead(int _netType, SocketPrivate_ACL* socket_acl_, SocketGather *gsd_)
	: running(true)
	, routeLinkTime(static_cast<unsigned int>(time(NULL)))
	, netType(_netType)
	, socket_acl(socket_acl_)
	, gsd_ptr(gsd_)
{

}

SocketGahterRead::~SocketGahterRead(void)
{
	running = false;
};

void* SocketGahterRead::run()
{
	if (NULL == socket_acl || NULL== gsd_ptr) 
	{
		CLogger::createInstance()->Log(MsgError,
			"SocketGahterRead start fail for socket_acl or gsd_ptr is NULL,[%s %s %d]!"
			, __FILE__, __FUNCTION__, __LINE__);
		return 0;
	}
	while (running)
	{
		read();
		check_link();
		data_time_up();
		usleep(1);
	}
	return NULL;
};


void SocketGahterRead::read()
{
	int re = socket_acl->Read(bufs);
	if (re <= 0) 
	{
		;
	}
	else {
		switch (netType)
		{
		case 1:
		{
			try {
				std::map<KeyObj_GClient, RDClient>::iterator it = bufs.begin();
				while (it != bufs.end())
				{
					unsigned char * buff = it->second.Buf;
					int start_pos = 0;
					unsigned char ctype = 0;
					// printf("read data:\n");
					for (int i = 0; i < it->second.len; i++)
					{
						// printf("%02X ",buff[i]);
						if (buff[i] > 0xf0) {
							if (buff[i] == 0xff) 
							{
								if (ctype) 
								{
									ctype = 0;
									ChannelCmd rdata(buff + start_pos, i - start_pos + 1,false,0,0,false, it->first.m_ip);
									gsd_ptr->add(rdata);
									start_pos = i + 1;
								}
							}
							else {
								ctype = buff[i];
								start_pos = i;
							}
						}
					}
					// printf("\n");
					buff = NULL;
					if (start_pos < it->second.len)
					{
						RDClient _newrd(it->second.Buf + start_pos, it->second.len - start_pos);
						it->second = _newrd;
						it++;
					}
					else {
#ifdef WIN32
						it = bufs.erase(it);
#else
						std::map<KeyObj_GClient, RDClient>::iterator ittemp = it++;
						bufs.erase(ittemp);
#endif
					}
				}
			}
			catch (const std::exception& e)
			{
				CLogger::createInstance()->Log(MsgError,
					"Data Deserialize false[%s],[%s %s %d]"
					, e.what()
					, __FILE__, __FUNCTION__, __LINE__);
			}
			catch (...) {
				CLogger::createInstance()->Log(MsgError,
					"Data Deserialize false,[%s %s %d]!"
					, __FILE__, __FUNCTION__, __LINE__);
			}
			ChannelCmd rdataGx;
			while (gsd_ptr->pop(rdataGx))
			{
				// unsigned char * pBuf = new unsigned char[rdataGx.len];
				// //反序列化处理
				// int nLen = pyfree::uncode(rdataGx.Buf, rdataGx.len, pBuf);
				// printf("\n*************2*%lu*********************\n",rdataGx.flag);
				gsd_ptr->AddFrame(rdataGx.flag, rdataGx.Buf, rdataGx.len);
				// delete[] pBuf;
				// pBuf = NULL;
			}
			break;
		}
		case 2:
		{
			try {
				std::map<KeyObj_GClient, RDClient>::iterator it = bufs.begin();
				while (it != bufs.end())
				{
					if (it->second.len > 0) 
					{
						ChannelCmd rdata(it->second.Buf, it->second.len,false,0,0,false, it->first.m_ip);
						gsd_ptr->add(rdata);
					}
					it++;
				}
				bufs.clear();
			}
			catch (const std::exception& e)
			{
				CLogger::createInstance()->Log(MsgError,
					"Exception for Reading and Parsing Error[%s],NetType(%d), [%s %s %d]"
					, e.what()
					, netType
					, __FILE__, __FUNCTION__, __LINE__);
			}
			catch (...) {
				CLogger::createInstance()->Log(MsgError,
					"Exception for Reading and Parsing Error,NetType(%d),[%s %s %d]!"
					, netType
					, __FILE__, __FUNCTION__, __LINE__);
			}
			ChannelCmd rdataGx;
			while (gsd_ptr->pop(rdataGx))
			{
				gsd_ptr->AddFrame(rdataGx.flag, rdataGx.Buf, rdataGx.len);
			}
			break;
		}
		default:
			break;
		}
	}
}

void SocketGahterRead::check_link()
{
	KeyObj_GClient linkFlag_;
	if (socket_acl->pop(linkFlag_))
	{
		/*
		linkFlag: 1 链接 -1 断开 0 可查性到,链接持续
		*/
		bool net_state = linkFlag_.linkFlag < 0?false : true;
		if (0 != linkFlag_.linkFlag) {
			CLogger::createInstance()->Log(MsgInfo,
				"Net link is changed,NetIp(%s),NetPort[%d],NetState[%d],[%s %s %d]!"
				, pyfree::intToIp(linkFlag_.m_ip).c_str()
				, linkFlag_.m_port
				, static_cast<int>(net_state)
				, __FILE__, __FUNCTION__, __LINE__);
		}
		gsd_ptr->setLink(linkFlag_.m_ip, net_state);
	}
}

void SocketGahterRead::data_time_up()
{
	//定期巡检上送那些长时间没更新或变化的数据
	if (routeLinkTime < static_cast<unsigned int>(time(NULL)))
	{
		routeLinkTime = static_cast<unsigned int>(time(NULL)) + 10;
		gsd_ptr->TimeUp();
	}
}